package com.jqsoft.launcher.activity.gairui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.garea.device.plugin.DevicePluginCategory;
import com.garea.device.plugin.DevicePluginManager;
import com.garea.device.plugin.IDevicePlugin;
import com.garea.device.plugin.idcard.IDCardInspector;
import com.garea.device.plugin.idcard.IIDCardDevice;
import com.garea.device.plugin.idcard.IIDCardPersonInfo;
import com.garea.device.plugin.idcard.OnIDCardListener;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.OlderPersonInfo;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.activity.bean.WorkpersonBean;
import com.jqsoft.launcher.activity.highblood.HBPFollowUpRecordActivity;
import com.jqsoft.launcher.activity.task.WebViewSWActivity;
import com.jqsoft.launcher.activity.task.WebViewZYYActivity;
import com.jqsoft.launcher.common.BphsConstants;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.patientdb.PatientDao;
import com.jqsoft.launcher.tool.AbstractViewHolder;
import com.jqsoft.launcher.util.CommonUtil;
import com.jqsoft.launcher.util.Log;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.StringTools;
import com.jqsoft.launcher.util.WebServiceUtils;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

//import cn.jqsoft.bphs.mpah.activity.gairui.CardActivity;


/**
 * 高血压确诊界面
 *
 * @author jiangbin
 */
public class OlderPersonManager extends JQActivity implements
        OnClickListener, OnScrollListener {
    private final String tag = "OlderPersonManager";
    private ListView listview;// 列表
    private ListAdapter adapter;




    // private LinearLayout ll_popup_xuanzhong;
    // private LinearLayout ll_popup_chakan;
    // private LinearLayout ll_popup_quxiao;

    private CheckBox xzCheckbox, current_xzCheckbox;
    // private PopupWindow popupWindow;
    private Button chaxuan_btn, evaluate, totalcount_bt, card_chaxuan_btn,
            drugservers, shangci_suifang_bt, xindian_jiance_bt;
    private EditText name_et, dangan_num_et, shengfenzheng_et;
    private String name_str, dangan_num_str, shengfenzheng_str;
    private String content;
    private List<OlderPersonInfo> infoList = new ArrayList<OlderPersonInfo>();
    private boolean notfirstTime = false, isThreadrun = false;
    private long allcount = 0;
    private String count;
    private View moreView;
    private LinearLayout progressBar_ll; // 更多等待层
    private Button moreButton;
    private TextView Readingtext;
    private OlderPersonInfo xuanzhong_tiao;

    private int jiciNum = 1;// 第几次点击加载更多
    private WorkpersonBean workbean;
    String shangciData, AllCount;

    // @Override
    // protected void onCreate(Bundle savedInstanceState) {
    // // TODO Auto-generated method stub
    // super.onCreate(savedInstanceState);
    // IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    // this.registerReceiver(mUsbReceiver, filter);
    //
    //
    // }

    @Override
    protected int getContentLayout() {
        return R.layout.olderpersonmanagers;
    }

    private IDCardInspector mInspector;
    private IIDCardDevice mDevice;

    @Override
    protected void initGui() {

        listview = (ListView) findViewById(R.id.hbp_diagnosis_lv);
        chaxuan_btn = (Button) findViewById(R.id.chaxuan_btn);
        chaxuan_btn.setOnClickListener(OlderPersonManager.this);
        evaluate = (Button) findViewById(R.id.evaluate);
        evaluate.setOnClickListener(OlderPersonManager.this);
        totalcount_bt = (Button) findViewById(R.id.totalcount_bt);
        dangan_num_et = (EditText) findViewById(R.id.dangan_num_et);
        name_et = (EditText) findViewById(R.id.name_et);
        shengfenzheng_et = (EditText) findViewById(R.id.shengfenzheng_et);
        //card_chaxuan_btn = (Button) findViewById(R.id.card_chaxuan_btn);
        UserLoginInfo info = UserLoginInfo.getInstances();
//		if (info.getsAndroidReader().equals("0")) {
//			card_chaxuan_btn.setVisibility(View.GONE);
//		}
//		card_chaxuan_btn.setOnClickListener(OlderPersonManager.this);
        drugservers = (Button) findViewById(R.id.drugservers);
        drugservers.setOnClickListener(OlderPersonManager.this);
        shangci_suifang_bt = (Button) findViewById(R.id.shangci_suifang_bt);
        shangci_suifang_bt.setOnClickListener(OlderPersonManager.this);

        mInspector = DevicePluginManager.getDeviceInspector(DevicePluginCategory.DEV_PLUGIN_CATEGORY_IDCARD_2,
                this);

        mInspector.setOnIDCardDevicePluginListener(new IDCardInspector.OnIDCardDevicePluginListener() {

            @Override
            public void onDiscoverDevice(IIDCardDevice dev) {
                Toast.makeText(OlderPersonManager.this,
                        "已连接", Toast.LENGTH_SHORT).show();
                mDevice = dev;
                //自动连接
                dev.setOnDevicePluginStateListener(new DevStateListener());
                dev.setOnIDCardListener(mCardListener);
                dev.init();
            }

            @Override
            public void onMonitorDevice(IIDCardDevice dev) {
                //USB不用本函数
            }

            @Override
            public void onRemovedDevice(IIDCardDevice dev) {
                if (mDevice != null) {
                    mDevice.close();
                    mDevice.uninit();
                    mDevice = null;
                }
            }
        });

        mInspector.init();
        mInspector.searchDevice();
    }

    private class DevStateListener implements IDevicePlugin.OnDevicePluginStateListener {


        public DevStateListener() {

        }

        @Override
        public void onDeviceOpened() {

        }

        @Override
        public void onDeviceInited() {
            mDevice.open();
        }

        @Override
        public void onDeviceUninited() {
            //
        }

        @Override
        public void onDeviceClosed() {
            //
        }

        @Override
        public void onStateChanged(int arg0, int arg1) {
            //
        }
    }

    private OnIDCardListener mCardListener = new OnIDCardListener() {

        @Override
        public void onReceived(IIDCardPersonInfo d) {
            shengfenzheng_et.setText(d.getID().trim());
            name_et.setText(d.getName().trim());
            xuanzhong_tiao = null;
            current_xzCheckbox = null;
            jiciNum = 1;
            moreButton.setVisibility(View.VISIBLE);
            name_str = name_et.getText().toString().trim();
            dangan_num_str = dangan_num_et.getText().toString().trim();
            shengfenzheng_str = shengfenzheng_et.getText().toString().trim();
            if (infoList.size() > 0) {
                listview.removeFooterView(moreView);
            }
            infoList.clear();
            allcount = 0;
            notfirstTime = false;
            loadWaitPanel();
            new Thread(sendable).start();

        }

        @Override
        public void onReadFailed() {
            Toast.makeText(OlderPersonManager.this,
                    "读卡失败", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void initAction() {
        setGoBack();
        // listview.setSelector(android.R.color.holo_orange_light);
        listview.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // PopupWindow popupWindow = new
                // PopupWindow(AppManagerActivity.this);
                OlderPersonInfo obj = (OlderPersonInfo) listview
                        .getItemAtPosition(position);
                try {
                    count = obj.getElderlyMedicineCount();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // if (obj instanceof OlderPersonInfo) {
                xuanzhong_tiao = obj;
                // }

                // dismissPopupWindow();
                // View contentView = View.inflate(getApplicationContext(),
                // R.layout.popup_item, null);
                // ll_popup_xuanzhong = (LinearLayout) contentView
                // .findViewById(R.id.ll_popup_xuanzhong);
                // ll_popup_chakan = (LinearLayout) contentView
                // .findViewById(R.id.ll_popup_chakan);
                // ll_popup_quxiao = (LinearLayout) contentView
                // .findViewById(R.id.ll_popup_quxiao);
                xzCheckbox = (CheckBox) view.findViewById(R.id.xuanzhong_cb);
                // ll_popup_xuanzhong.setOnClickListener(OlderPersonManager.this);
                // ll_popup_chakan.setOnClickListener(OlderPersonManager.this);
                // ll_popup_quxiao.setOnClickListener(OlderPersonManager.this);
                // LinearLayout ll_popup_container = (LinearLayout) contentView
                // .findViewById(R.id.ll_popup_container);
                // ScaleAnimation sa = new ScaleAnimation(0.0f, 1.0f, 0.0f,
                // 1.0f);
                // sa.setDuration(300);
                // // Object obj = listview.getItemAtPosition(position);
                // // if (obj instanceof AppInfo) {
                // // AppInfo appinfo = (AppInfo) obj;
                // // clickedpackname = appinfo.getPackname();
                // // if (appinfo.isUserapp()) {
                // // ll_uninstall.setTag(true);
                // // } else {
                // // ll_uninstall.setTag(false);
                // // }
                // // } else {
                // // return;
                // // }
                // int top = view.getTop();
                // int bottom = view.getBottom(); //pix
                // popupWindow = new PopupWindow(contentView,
                // AndroidUtil.dip2px(getApplicationContext(), 400), bottom -
                // top
                // + AndroidUtil.dip2px(getApplicationContext(), 40));
                // // 注意:一定要给popwindow设置背景图片.背景资源.
                // popupWindow.setBackgroundDrawable(new ColorDrawable(
                // Color.TRANSPARENT));
                // // 如果不设置背景资源 , 动画, 焦点的处理 都会产生问题.
                // int[] location = new int[2];
                // view.getLocationInWindow(location);
                // popupWindow.showAtLocation(view, Gravity.TOP| Gravity.LEFT ,
                // location[0] + 500, location[1]-20);
                // // 播放一个缩放的动画.
                // ll_popup_container.startAnimation(sa);

                for (int i = 0; i < infoList.size(); i++) {
                    infoList.get(i).setCheck(false);
                }
                obj.setCheck(true);
                if (current_xzCheckbox != null) {
                    current_xzCheckbox.setChecked(false);
                }
                xzCheckbox.setChecked(true);
                current_xzCheckbox = xzCheckbox;
                adapter.notifyDataSetChanged();
            }

        });

        listview.setOnScrollListener(this);

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            workbean = (WorkpersonBean) bundle.get("WorkpersonBean");
            if (workbean != null) {
                shengfenzheng_str = workbean.getsCardNo();
                name_str = workbean.getsPersonName();
                dangan_num_str = workbean.getsNo();
                loadWaitPanel();
                new Thread(sendable).start();
            }
        }
    }

    @Override
    protected void initData() {
        setTitle("老年人管理");
        // if (BphsConstants.sAndroidReader) {
        // chaxuan_btn.setText("读身份证查询");
        // dangan_num_et.setEnabled(false);
        // name_et.setEnabled(false);
        // shengfenzheng_et.setEnabled(false);
        // dangan_num_et.setBackgroundDrawable(getResources().getDrawable(
        // drawable.shape_grayall_corner));
        // name_et.setBackgroundDrawable(getResources().getDrawable(
        // drawable.shape_grayall_corner));
        // shengfenzheng_et.setBackgroundDrawable(getResources().getDrawable(
        // drawable.shape_grayall_corner));
        // }
        moreView = getLayoutInflater().inflate(
                R.layout.finance_fund_pagination_more, null);
        moreButton = (Button) moreView.findViewById(R.id.loadMore);
        moreButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (notfirstTime && (allcount > infoList.size())
                        && !isThreadrun) {
                    moreButton.setVisibility(View.GONE);
                    progressBar_ll.setVisibility(View.VISIBLE);
                    // loadWaitPanel();
                    // 开线程去下载网络数据
                    // handler.postDelayed(sendable, 0);
                    jiciNum++;
                    new Thread(sendable).start();
                }

            }
        });
        progressBar_ll = (LinearLayout) moreView
                .findViewById(R.id.progressBar_ll);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        dismissrogressBar();
        switch (requestCode) {
            case 1:
               // infoList.clear();
                notfirstTime  = false;
                new Thread(sendable).start();
                break;
            case 2:
               // infoList.clear();
                notfirstTime  = false;
                new Thread(sendable).start();
                break;
        }

    }

    //
    private  Handler myhandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.MSG_LOAD_OVER:
                    adapter = new ListAdapter();
                    notfirstTime = true;
                    if (!(infoList.size() == allcount || allcount == 0 || infoList
                            .size() <= 0)) {
                        // listview.removeFooterView(moreView);
                        listview.addFooterView(moreView);
                    }
                    listview.setAdapter(adapter);

                    String count;
                    if (infoList.size() > allcount) {
                        count = "共计" + infoList.size() + "条）";
                    } else {
                        count = "共计" + allcount + "条）";
                    }
                    totalcount_bt.setText("（已加载" + infoList.size() + "条/" + count);
                    if (infoList.size() == 0) {
                        MessageTools.showDialogOk(ctx, "无此人信息");
                    }
                    adapter.notifyDataSetChanged();
                    dismissrogressBar();
                    progressBar_ll.setVisibility(View.GONE);
                    break;
                case Constant.SHOW_UPDATE:
                    totalcount_bt.setText("（已加载" + infoList.size() + "条/" + "共计"
                            + allcount + "条）");
                    if (infoList.size() >= allcount) {
                        listview.removeFooterView(moreView);
                    } else {
                        progressBar_ll.setVisibility(View.GONE);
                        moreButton.setVisibility(View.VISIBLE);
                    }
                    adapter.notifyDataSetChanged();
                    // dismissrogressBar();
                    break;
                case Constant.MSG_LOAD_ERROR:
                    dismissrogressBar();
                    MessageTools.showDialogOk(ctx, "请填写至少一项查询条件,建议填写姓名！");
                    break;

                case Constant.UPDATE_NORMOL:
                    dismissrogressBar();
                    if (AllCount.equals("0")) {
                        MessageTools.showDialogOk(ctx, "暂时无随访");
                        return;
                    } else {
                        Intent intent1 = new Intent(act,
                                HBPFollowUpRecordActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("shangciData", shangciData);
                        intent1.putExtras(bundle);
                        startActivity(intent1);
                    }
                    break;
            }
            isThreadrun = false;
        }
    };

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        // dismissPopupWindow();
        if (firstVisibleItem + visibleItemCount == totalItemCount
                && notfirstTime && (allcount > infoList.size()) && !isThreadrun) {
            // loadWaitPanel();
            // //开线程去下载网络数据
            // new Thread(sendable).start();
        }
    }

    // 请求服务器
    private Runnable sendable = new Runnable() {

        public void run() {
            if (!BphsConstants.isNetAvailable) {
                PatientDao dao = new PatientDao(ctx);
                if (StringTools.isNotBlank(name_str)) {
                    // infoList = dao.getGroupList("sPersonName", name_str);
                    myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
                } else if (StringTools.isNotBlank(shengfenzheng_str)) {
                    // infoList = dao.getGroupList("sCardNo", shengfenzheng_str);
                    myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
                } else if (StringTools.isNotBlank(dangan_num_str)) {
                    // infoList = dao.getGroupList("sNo", dangan_num_str);
                    myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
                } else {
                    myhandler.sendEmptyMessage(Constant.MSG_LOAD_ERROR);
                }
            } else {
                isThreadrun = true;
                String requestUrl = BphsURL
                        .getCommonPath("GetOldPeopleManageData_URL");
                Log.i(tag, "查询:content" + requestUrl);
                String methodName = BphsURL
                        .getCommonPath("GetOldPeopleManageData_METHOD");//GetOldPeopleManageData
                JSONObject data = new JSONObject();
                // {"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10000000","sPersonName":"陈艳林","sCardNo":"340824195312281418","type":"4"}
                try {
                    UserLoginInfo info = UserLoginInfo.getInstances();
                    data.put("sAreaCode", info.getsManagementDivisionCode());//
                    if (jiciNum != 0) {
                        data.put("iCurrentPageIndex", jiciNum + "");// (jiciNum
                        // * 10 + 1)
                    } else {
                        data.put("iCurrentPageIndex", "1");
                    }
                    data.put("iPageSize", "10"); //
                    data.put("sNo", dangan_num_str); //
                    // data.put("sPersonName", "陈艳林"); //
                    // data.put("sCardNo", "340824195312281418"); //
                    data.put("sPersonName", name_str); //
                    data.put("sCardNo", shengfenzheng_str); //
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
                content = WebServiceUtils.requestByParams(methodName,
                        data.toString(), requestUrl);
                if (StringUtils.isNotBlank(content)) {
                    try {
                        Log.i(tag, "返回的查询结果" + content);
                        // String result= content.replaceAll("\\\\", "");
                        // Log.i(tag, "返回的查询结果"+result);
                        JSONObject json = new JSONObject(content);
                        // Log.i(tag, "返回的查询结果"+result);"AllCount":0,
                        // allcount= 28;
                        allcount = json.getLong("AllCount");
                        if (allcount == 0) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    MessageTools.showDialogOk(ctx, "暂无此人信息");
                                }
                            });

                        }
                        JSONObject jo = new JSONObject(json.getString("Data"));
                        JSONArray jsonArray = (JSONArray) jo.get("Table");
                        for (int i = 0; i < jsonArray.length(); ++i) {
                            JSONObject o = (JSONObject) jsonArray.get(i);
                            OlderPersonInfo info = new OlderPersonInfo(
                                    o.getString("sNo"),
                                    o.getString("sPersonName"),
                                    o.getString("sSexName"),
                                    o.getString("dBirthday"),
                                    o.getString("sCardNo"),
                                    o.getString("ElderlyMedicineCount"),
                                    o.getString("SelfAssessmentCount"),
                                    o.getString("dCreateTime"),
                                    o.getString("dAddTime"),
                                    o.getString("sInputDeptName"),
                                    o.getString("sPersonID"),
                                    o.getString("sHomeAddress"),
                                    o.getString("sAddUser")

                            );
                            if (allcount == 1) {
                                // info.setCheck(true);
                                xuanzhong_tiao = info;

                            }

                            infoList.add(info);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (notfirstTime) {
                        myhandler.sendEmptyMessage(Constant.SHOW_UPDATE);
                    } else {
                        myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
                    }
                } else {

                }
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.chaxuan_btn:// 查询按钮
                // if (!BphsConstants.sAndroidReader) {
                xuanzhong_tiao = null;
                current_xzCheckbox = null;
                jiciNum = 1;
                moreButton.setVisibility(View.VISIBLE);
                name_str = name_et.getText().toString().trim();
                dangan_num_str = dangan_num_et.getText().toString().trim();
                shengfenzheng_str = shengfenzheng_et.getText().toString().trim();
                if (infoList.size() > 0) {
                    listview.removeFooterView(moreView);
                }
                infoList.clear();
                allcount = 0;
                notfirstTime = false;
                loadWaitPanel();
                new Thread(sendable).start();
                // } else {
                // loadWaitPanel();
                // Intent intent = new Intent(this, CardActivity.class);
                // startActivityForResult(intent, 1);
                // }
                return;
            case R.id.evaluate://自理评估
                if (current_xzCheckbox == null) {
                    MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
                    return;
                }
                // if (current_xzCheckbox == null) {
                // MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
                // return;
                // }
                if (xuanzhong_tiao != null) {
                    Intent intent = new Intent(act, WebViewSWActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("OlderPersonInfo", xuanzhong_tiao);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 1);
                } else {
                    toNoFinish(WebViewSWActivity.class);
                }
                return;

            case R.id.drugservers://中医药服务
                if (current_xzCheckbox == null) {
                    MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
                    return;
                }
                if (xuanzhong_tiao != null) {
                    Intent intent = new Intent(act, WebViewZYYActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("OlderPersonInfo", xuanzhong_tiao);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 2);
                } else {
                    toNoFinish(WebViewZYYActivity.class);
                }
                // toNoFinish(SubmitInfoListActivity.class);
                break;
            case R.id.shangci_suifang_bt:
                if (!BphsConstants.isNetAvailable) {
                    MessageTools.showDialogOk(ctx, "此功能暂不支持离线操作，请连线操作！");
                    return;
                } else if (current_xzCheckbox == null) {
                    MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
                    return;
                }
                // if (current_xzCheckbox == null) {
                // MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
                // return;
                // }
                else {
                    loadWaitPanel();
                    new Thread() {
                        public void run() {
                            if (!TextUtils.isEmpty(xuanzhong_tiao.getsPersonID())) {
                                String temp = WebServiceUtils.requestSuifang(
                                        xuanzhong_tiao.getsPersonID(), "1");
                                shangciData = WebServiceUtils.StringSplit(temp);
                                AllCount = WebServiceUtils.StringSplit2(temp);
                                myhandler.sendEmptyMessage(Constant.UPDATE_NORMOL);
                            }

                        }

                        ;
                    }.start();
                }

                break;

            case R.id.xindian_jiance_bt:// 心电检测按钮
                if (1 != BphsConstants.deviceBranchType) {
                    MessageTools.showDialogOk(ctx, "此功能暂时只支持盖瑞设备！");
                    return;
                }

                if (current_xzCheckbox == null && infoList.size() > 1) {
                    MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
                    return;
                }
                if (xuanzhong_tiao != null) {
                    Intent intent0 = new Intent(act, XDpersonActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("sPersonID", xuanzhong_tiao.getsPersonID());
                    bundle.putString("sNo", xuanzhong_tiao.getsNo());
                    bundle.putString("sPersonName", xuanzhong_tiao.getsPersonName());
                    bundle.putString("sCardNo", xuanzhong_tiao.getsCardNo());
                    intent0.putExtras(bundle);
                    startActivity(intent0);
                } else {
                    toNoFinish(XDpersonActivity.class);
                }
                return;

            case R.id.ll_popup_xuanzhong:
                if (current_xzCheckbox != null) {
                    current_xzCheckbox.setChecked(false);
                }
                xzCheckbox.setChecked(true);
                current_xzCheckbox = xzCheckbox;
                break;
            case R.id.ll_popup_chakan:
                // toNoFinish(HBPCheckListActivity.class);
                break;
//			case R.id.card_chaxuan_btn:
//				// Intent intent = new Intent(this, TestJarActivity.class);
//				// startActivityForResult(intent, 1);
//				loadWaitPanel();
//				// Intent intent = new Intent(this, CardActivity.class);
//				// startActivityForResult(intent, 1);
//				return;
        }
        // dismissPopupWindow();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d(tag, "屏蔽 home,back,menu键keyCode:" + keyCode);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // if (popupWindow != null && popupWindow.isShowing()) {
            // popupWindow.dismiss();
            // popupWindow = null;
            // return true;
            // }
            Log.d(tag, "BACK键捕获。to BACK");
            act.finish();
            act.overridePendingTransition(android.R.anim.slide_in_left,
                    android.R.anim.slide_out_right);
            return true;
        }
        if (KeyEvent.KEYCODE_HOME == keyCode) {
            // if (popupWindow != null && popupWindow.isShowing()) {
            // popupWindow.dismiss();
            // popupWindow = null;
            // return true;
            // }
            Log.d(tag, "home键捕获。to home");
            toHome();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDevice != null) {
            mDevice.close();
            mDevice.uninit();
        }

        if (mInspector != null) {
            mInspector.uninit();
        }
    }

    // 关闭pop窗口
    // private void dismissPopupWindow() {
    // if (popupWindow != null && popupWindow.isShowing()) {
    // popupWindow.dismiss();
    // popupWindow = null;
    // }
    // }

    private class ListAdapter extends BaseAdapter {

        public int getCount() {
            // Log.d(tag, "列表的大小" + functionList.size());
            // return functionList.size();
            return infoList.size();
        }

        public Object getItem(int position) {
            // return functionList.get(position);
            return infoList.get(position);
        }

        public long getItemId(int position) {

            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
//            // ViewHolder holder;
//            LayoutInflater inflater = LayoutInflater.from(act);
//            // if (convertView == null) {
//            // holder = new ViewHolder();
//            convertView = inflater.inflate(R.layout.item_oldermanger, null);
//            // holder.iv_function_icon = (ImageView) convertView
//            // .findViewById(R.id.iv_function_icon);
//            TextView dangan_num_tv = (TextView) convertView
//                    .findViewById(R.id.dangan_num_tv);
//            TextView name_tv = (TextView) convertView
//                    .findViewById(R.id.name_tv);
//            TextView sex_tv = (TextView) convertView.findViewById(R.id.sex_tv);
//            TextView age_tv = (TextView) convertView.findViewById(R.id.age_tv);
//            TextView shengfenzheng_tv = (TextView) convertView
//                    .findViewById(R.id.shengfenzheng_tv);
//            TextView jibie_tv = (TextView) convertView
//                    .findViewById(R.id.jibie_tv);
//            TextView quezheng_yiyuan_tv = (TextView) convertView
//                    .findViewById(R.id.quezheng_yiyuan_tv);
//            TextView quezheng_date_tv = (TextView) convertView
//                    .findViewById(R.id.quezheng_date_tv);
//            // holder.luru_danwei_tv = (TextView) convertView
//            // .findViewById(R.id.luru_danwei_tv);
//            TextView suifang_cishu_tv = (TextView) convertView
//                    .findViewById(R.id.suifang_cishu_tv);
//            // holder.tijian_cishu_tv = (TextView) convertView
//            // .findViewById(R.id.tijian_cishu_tv);
//            // holder.shifou_guanli_tv = (TextView) convertView
//            // .findViewById(R.id.shifou_guanli_tv);
//            // convertView.setTag(holder);
//            CheckBox cb = (CheckBox) convertView
//                    .findViewById(R.id.xuanzhong_cb);
//            // } else {
//            // holder = (ViewHolder) convertView.getTag();
//            // }

            LayoutInflater inflater = LayoutInflater.from(act);
            if (convertView==null) {
                convertView = inflater.inflate(R.layout.item_oldermanger, null);
            }
            TextView dangan_num_tv = (TextView) AbstractViewHolder.get(convertView, R.id.dangan_num_tv);
            TextView name_tv = (TextView) AbstractViewHolder.get(convertView, R.id.name_tv);
            TextView sex_tv = (TextView) AbstractViewHolder.get(convertView, R.id.sex_tv);
            TextView age_tv = (TextView) AbstractViewHolder.get(convertView, R.id.age_tv);
            TextView shengfenzheng_tv = (TextView) AbstractViewHolder.get(convertView, R.id.shengfenzheng_tv);
            TextView jibie_tv = (TextView) AbstractViewHolder.get(convertView, R.id.jibie_tv);
            TextView quezheng_yiyuan_tv = (TextView) AbstractViewHolder.get(convertView, R.id.quezheng_yiyuan_tv);
            TextView quezheng_date_tv = (TextView) AbstractViewHolder.get(convertView, R.id.quezheng_date_tv);
            TextView suifang_cishu_tv = (TextView) AbstractViewHolder.get(convertView, R.id.suifang_cishu_tv);
            CheckBox cb = (CheckBox) AbstractViewHolder.get(convertView, R.id.xuanzhong_cb);

            dangan_num_tv.setText(infoList.get(position).getsNo());
            name_tv.setText(infoList.get(position).getsPersonName());
            sex_tv.setText(infoList.get(position).getsSexName());

            age_tv.setText(CommonUtil.calcAge2(infoList.get(position).getdBirthday()) + "");
            shengfenzheng_tv.setText(infoList.get(position).getsCardNo());
            jibie_tv.setText(getdatas(CommonUtil.String2date(infoList
                    .get(position).getdCreateTime())));
            quezheng_yiyuan_tv.setText(infoList.get(position).getsHomeAddress());
            quezheng_date_tv.setText(infoList.get(position).getElderlyMedicineCount());
//            // holder.luru_danwei_tv.setText(infoList.get(position)
//            // .getsInputDeptName());
            suifang_cishu_tv.setText(infoList.get(position).getSelfAssessmentCount());
            // holder.tijian_cishu_tv.setText(infoList.get(position)
            // .getHealthyCheckUpCount());
            // holder.shifou_guanli_tv.setText("-1".equals(infoList.get(position)
            // .getiState())?"否":"是");

                cb.setChecked(infoList.get(position).isCheck());
                if (cb.isChecked()) {
                    convertView.setBackgroundColor(Color.parseColor("#ff00CED1"));
                }
                else {
                    convertView.setBackgroundColor(Color.WHITE);
                }

            return convertView;
        }
    }

    // static class ViewHolder {
    // // ImageView iv_function_icon;
    // TextView dangan_num_tv, name_tv,sex_tv
    // ,age_tv,shengfenzheng_tv,jibie_tv,quezheng_yiyuan_tv
    // ,quezheng_date_tv,suifang_cishu_tv;
    // // luru_danwei_tv tijian_cishu_tv shifou_guanli_tv
    // }
    public static String getdatas(String Resouce) {
        String reSut = "";
        try {
            SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
            reSut = f.format(f.parse(Resouce.replace("/", "-")));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return reSut;
    }



    @Override
    public void onPause() {
        super.onPause();
        // mAdapter.disableForegroundDispatch(this);

    }

    @Override
    protected void onResume() {
        super.onResume();

    }





    public void getIDCARDINFO() {
        jiciNum = 1;
        moreButton.setVisibility(View.VISIBLE);
        name_str = name_et.getText().toString().trim();
        dangan_num_str = dangan_num_et.getText().toString().trim();
        shengfenzheng_str = shengfenzheng_et.getText().toString().trim();
        if (infoList.size() > 0) {
            listview.removeFooterView(moreView);
        }
        infoList.clear();
        allcount = 0;
        notfirstTime = false;
        loadWaitPanel();
        new Thread(sendable).start();
    }


}
